package com.feiluan.interceptor;


import com.feiluan.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class HeaderHandlerInterceptor implements ClientHttpRequestInterceptor {

    @Autowired
    private TokenService tokenService;

    private static String NOTICE_MESSAGE_HOST = "39.99.205.81:81";

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        String authority = httpRequest.getURI().getAuthority();
        if (NOTICE_MESSAGE_HOST.equals(authority)) {
            HttpHeaders headers = httpRequest.getHeaders();
            boolean contains = headers.containsKey("accessToken");
            Boolean isGetAccessToken = httpRequest.getURI().toString().contains("getAccessToken");
            if (!contains && !isGetAccessToken) {
                headers.add("accessToken", tokenService.getAccessToken());
            }
        }
        //继续执行请求
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }


}



